using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using ProduceBasicData.Api.Application.Command.WarehouseManage;
using ProduceBasicData.Domain.WarehouseManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure;
using ProduceBasicData.Infrastructure.Interface;
using ProduceBasicData.Api.Services;

namespace ProduceBasicData.Api.Application.Handler.WarehouseManage
{
    /// <summary>
    /// 创建出库单处理器
    /// </summary>
    public class CreateStockOutOrderHandler : IRequestHandler<CreateStockOutOrderCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<StockOutOrder> _stockOutOrderRepository;
        private readonly IBaseRespository<StockOutOrderItem> _stockOutOrderItemRepository;
        private readonly IMapper _mapper;
        private readonly MyDBContext _myDBContext;
        private readonly ICodeRuleService codeRuleService;

        public CreateStockOutOrderHandler(
            IBaseRespository<StockOutOrder> stockOutOrderRepository,
            IBaseRespository<StockOutOrderItem> stockOutOrderItemRepository,
            IMapper mapper, MyDBContext myDBContext,ICodeRuleService codeRuleService)
        {
            _stockOutOrderRepository = stockOutOrderRepository;
            _stockOutOrderItemRepository = stockOutOrderItemRepository;
            _mapper = mapper;
            _myDBContext = myDBContext;
            this.codeRuleService = codeRuleService;
        }

        /// <summary>
        /// 处理创建出库单请求
        /// </summary>
        /// <param name="request">创建出库单命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<int>> Handle(CreateStockOutOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {

                // 创建事务
                using var transaction = await _myDBContext.Database.BeginTransactionAsync(cancellationToken);
                try
                {
                    // 映射命令到领域模型
                    var stockOutOrder = _mapper.Map<StockOutOrder>(request);

                    //编码
                    if (string.IsNullOrEmpty(stockOutOrder.OrderNumber))
                    {
                        var code = await codeRuleService.AutoGenerateCodeAsync("ProduceBasicData.Domain.WarehouseManage.StockOutOrder");
                        if (!string.IsNullOrEmpty(code))
                        {
                            stockOutOrder.OrderNumber = code;
                        }
                        else
                        {
                            stockOutOrder.OrderNumber = $"CKD{DateTime.Now:yyyyMMddHHmmss}";
                        }
                    }

                    // 保存出库单
                    await _stockOutOrderRepository.AddAsync(stockOutOrder);

                    // 处理出库单明细
                    if (request.Items != null && request.Items.Any())
                    {
                        foreach (var itemCommand in request.Items)
                        {
                            var item = _mapper.Map<StockOutOrderItem>(itemCommand);
                            item.StockOutOrderId = stockOutOrder.Id;
                            await _stockOutOrderItemRepository.AddAsync(item);
                        }
                    }

                    await _myDBContext.SaveChangesAsync(cancellationToken);
                    // 提交事务
                    await transaction.CommitAsync();

                    return new ApiResult<int>
                    {
                        Data = stockOutOrder.Id,
                        Code = ApiEnum.Success,
                        Msg = "出库单录入成功"
                    };
                }
                catch (Exception)
                {
                    // 回滚事务
                    await transaction.RollbackAsync();
                    throw;
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"出库单录入失败,{ex.Message}"
                };
            }
        }
    }
}